//合同一览
<template>
  <div class="flex-1 flex-ver">
    <div class="mb8">
      <search @clearSearch='clearSearch' :status='true'>
        <el-form label-width='93px' inline autocomplete="off"  :model="pageparm" class="search_box">
          <el-form-item label="合同名称">
            <el-input size="medium" clearable v-model="pageparm.name" placeholder="请输入合同名称搜索"/>
          </el-form-item> 
          <el-form-item label="合同类型">
            <el-select size="medium" v-model="pageparm.contract_type" clearable @change='searchChane($event,"contract_type")'  placeholder="请选择合同类型" >
              <el-option
                  v-for="item in contractType"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="负责人姓名">
            <inputSearch ref="search_e" placeholder="请输入负责人姓名搜索" @onChange='searchChane($event,"leader_id")'  />
          </el-form-item> 
          <el-form-item label="负责人类型">
            <el-select size="medium" v-model="pageparm.leader_type" clearable  @change='searchChane($event,"leader_type")'  placeholder="请选择负责人类型" >
              <el-option
                  v-for="item in leaderType"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="科室" v-if="adminShow">
            <inputSearch ref="search_d" type='departments' @onChange='searchChane($event,"departments_id")'  />
          </el-form-item>
          <el-form-item label="开始日期">
            <el-date-picker
              v-model="pageparm.start_time"
              type="daterange"
              range-separator="至"
              start-placeholder="日期范围"
              end-placeholder="日期范围"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              @change="searchChane($event,'start_time')">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="终止日期">
            <el-date-picker
              v-model="pageparm.end_time"
              type="daterange"
              range-separator="至"
              start-placeholder="日期范围"
              end-placeholder="日期范围"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              @change="searchChane($event,'end_time')">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="审核状态">
            <el-select size="medium" clearable v-model="pageparm.review_status" placeholder="请选择审核状态搜索" @change='searchChane($event,"review_status")'>
              <el-option
                v-for="item in reviewStatus"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <p slot="footer" class="flex-1 tx-r c-6">
          <svg class="icon f-20" aria-hidden="true" slot="image">
            <use xlink:href="#icon-tishi"></use>
          </svg>温馨提示：立项审核通过，并且不处于变更状态中的项目才能提交结项申请。
        </p>
      </search>
    </div>
    <el-table
      :data="tableData"
      class="flex-1"
      height="100%" size="medium" 
      border 
      highlight-current-row
      v-loading="tableLoading"
      stripe
      @sort-change="tableSortChange"
      @row-click='viewDetails'>  
      <el-table-column
        align="center"
        v-for="(item,i) in headerList"
        :key="item.prop"
        :prop="item.prop"
        :label="item.label + (item.unit || '')"
        :width="item.width"
        :fixed="i === 0 ? true: false"
        show-overflow-tooltip
        :sortable="item.noSort?false:'custom'">
        <template slot-scope="scope">
          <template v-if="item.prop === 'departments_id'">
            {{ scope.row.department?scope.row.department.name:'' }}
          </template>
          <template v-else-if="item.prop === 'leader_id'">
            {{ scope.row.leader_info?scope.row.leader_info.name:''}}
          </template>
          <template v-else-if="item.prop === 'complete_id'">
            {{objToStr(scope.row.complete_name)}}
          </template>
          <template v-else-if="item.prop === 'review_status'">
            <span v-if="scope.row.review.review_comment" class="c-red">{{scope.row.status}}：{{scope.row.review.review_comment}} </span>
            <span v-else>{{scope.row.status}}</span>
          </template>
          <template v-else-if="item.prop === 'contract_type'">
            {{ echo(scope.row.contract_type,contractType) }}
          </template>
          <template v-else-if="item.prop === 'leader_type'">
            {{ echo(scope.row.leader_type,leaderType) }}
          </template>
          <template v-else>
           {{ scope.row[item.prop] }}
          </template>
        </template>
      </el-table-column>
      <el-table-column fixed="right" align="center" label="操作" width="120">
        <div class="" slot-scope="scope">
          <el-tooltip effect="dark" content="提交结项材料" placement="bottom-end" >
            <el-button v-if="scope.row.final" type="success" @click.stop="submitMaterials(scope.row)" size="small" icon="el-icon-s-promotion" circle></el-button>
          </el-tooltip>
          <!-- <el-tooltip  effect="dark" content="上传文件" placement="bottom-end" >
            <el-button type="primary" @click.stop="handle(scope.row)" size="small"  icon="el-icon-document-add" circle></el-button>
          </el-tooltip> -->
          <el-tooltip  effect="dark" content="查看结项审核结果" placement="bottom-end" v-if="scope.row.finalReview">
            <el-button type="primary" @click.stop="viewMiddleReview(scope.row.finalReview)" size="small"  icon="el-icon-warning-outline" circle></el-button>
          </el-tooltip>
        </div>
      </el-table-column>
    </el-table>

    <Pagination v-bind:child-msg="pageparm" @callFather="callFather"></Pagination>

    <el-dialog :visible.sync="editFormVisible" width="680px" @close='dialogClose'
    :close-on-click-modal='false'
    :close-on-press-escape='false'>
      <h2 slot="title" class="tx-c">文件上传</h2>
      <el-form
      autocomplete="off"
      label-width="100px"
      class="form">
        <el-form-item v-for="(v,i) in upfilesObj" :key="'label' + v" :label="v">
          <div style="width: 500px">
              <p><el-upload
                  multiple
                  action="/"
                  :on-change="(file, fileList) => {onChangeFile(file, fileList, i)}"
                  :on-remove="(file, fileList) => {onRemoveFile(file, fileList, i)}"
                  :auto-upload="false"
                  :file-list='fileObj[i]'>
                  <el-button size="medium" type="primary">选择文件</el-button>
              </el-upload></p>
              <div>
                <p v-for="(v) in uploadedList[i]" :key="'ed_' + v.id" class="p_cell flex-space-between"> 
                  <span class="overhide_ shou" @click="uploadFiles(v.file_path,v.file_name)"> 
                    <i class="el-icon-document"></i> {{v.file_name}}
                  </span> 
                  <i @click="delFiles(v.id,i)" class="el-icon-close mr4 shou"></i>
                </p>
              </div>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="flex-justify-bcenter">
        <el-button @click="editFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit" :loading='btnLoading'>确 定</el-button>
      </div>
    </el-dialog>
    <!-- 审核 -->
    <examine ref="examine" :item='examine_item' />   

    <htdetails :info='details' ref="detail"  />
  </div>
</template>

<script>

import {
    Apicontracts,
    ApicontractsChange,
    ApiupLoadFiles,
} from '@/api'
import {reviewStatus,leaderType,reviewerTypeObj,reviewStatusObj} from "@/assets/js"
import { debounce,adminShow,objToStr } from "@/utils/index";
import {headerList,contractType} from '../js/transverse'
import htdetails from "./htdetails.vue"
export default {
  name: 'project_transverse_htclosing',
  components:{
    htdetails,
  },
  data(){
    return{
      objToStr,
      adminShow:adminShow(),
      reviewStatus,
      leaderType,
      contractType,

      tableData:[], 
      editForm: {},  //修改或者查看详情
      editFormVisible: false,
      btnLoading: false,
      pageparm: {
        page: 1,
        perPage: 20,
        total: null,
        sort_str: null, 
        sort_order: 'desc' ,
      },
      tableLoading: false,

      headerList,

      examine_item:{
        view: false
      },

      id:null,

      details:{
        review:{}
      },

      upfilesObj:{
        5: '结题报告',
        6: '结题证明',
        // 7: '验收报告'
      },
      fileObj:{5:[],6:[],},
      uploadedList:{5:[],6:[],},
      del:[],
    }
  },
  mounted(){
    this.getList()
  },
  methods:{
    dialogClose(){
      for (const key in this.fileObj) {
        this.fileObj[key] = []
        this.uploadedList[key] = []
      }
      this.del = []
    },
    handle(value){
      this.editForm = {...value}
    },
    uploadFiles: debounce(function (url,name){
      ApiupLoadFiles(url).then(res => {
          let a = document.createElement("a")
          a.href = URL.createObjectURL(res)
          a.download = name
          a.click()
          URL.revokeObjectURL(a.href)
      })
    },500,true),
    viewDetails(val,){
      this.details = val
      this.$refs.detail.showInfo = true
    },
    viewMiddleReview(val){
      this.examine_item.review_status = val.review_status
      this.examine_item.review_comment = val.review_comment
      this.examine_item.view = true
      this.$refs.examine.examineShow = true
    },
    delFiles(id,i){
      this.del.push(id)
      this.uploadedList[i] = this.uploadedList[i].filter(item => item.id !== id)
    },
    submitMaterials(val){
      this.id = val.id
      for (const key in this.uploadedList) {
        this.uploadedList[key] = JSON.parse(JSON.stringify(val.files[key] || []))
      }
      this.editFormVisible = true
    },
    onChangeFile(file, fileList,i){
      this.fileObj[i].push(file)
    },
    onRemoveFile(file, fileList,i){
      this.fileObj[i] = fileList
    },
    submit(){
      const fileObj = this.fileObj
      let count = 0
      for (const key in fileObj) {
        count += (fileObj[key].length + this.uploadedList[key].length)
      }
      if(count === 0){
        this.$message.error('至少上传一个文件')
        return
      }
      this.btnLoading = true
      const formData = new FormData()
      formData.append('reviewer_type',4)
      for (const key in fileObj) {
        if(fileObj[key].length > 0){
          fileObj[key].forEach(ele => {
            formData.append(`${key}[]`,ele.raw)
          });
        }
      }
      if(this.del.length > 0){
        this.del.forEach(item => {
          formData.append(`del[]`,item)
        })
      }else{
        formData.append(`del[]`,[])
      }
      ApicontractsChange(formData,this.id,{
        headers:{'Content-Type':'multipart/form-data'}
      }).then(res => {
        this.$message.success('提交结项材料成功')
        this.btnLoading = false
        this.editFormVisible = false
        this.getList()
      }).catch(()=>{
        this.btnLoading = false
        this.$message.error('提交结项材料失败')
      })
    },
    //审核
    echo(i,arr){
      let label
      for (const item of arr) {
        if(item.value === i){
          label = item.label
          break;
        }
      }
      return label
    },
    tableSortChange(column){
      if (column.order === "descending") {
        this.pageparm.sort_str = column.prop;
        this.pageparm.sort_order = "desc";
      } else if (column.order === "ascending") {
        this.pageparm.sort_str = column.prop;
        this.pageparm.sort_order = "asc";
      }else{
        this.pageparm.sort_str = null;
        this.pageparm.sort_order = null;
      }
      this.getList()
    },
    //搜索
    clearSearch(){
      this.$refs.search_e.clear()
      if(this.adminShow) this.$refs.search_d.clear()
    },
    searchChane(i,val){
      this.pageparm[val] = i
      this.pageparm.page = 1
      this.getList()
    },
    //分页
    callFather(pageparm){
      this.pageparm.page = pageparm.page
      this.pageparm.perPage = pageparm.perPage
      this.getList()
    },
    getList(){
      this.pageparm.type = 'final'
      this.tableLoading = true
      Apicontracts(this.pageparm).then(({data,page}) => {
        this.tableData = data || []
        this.pageparm.total = page.total
        this.tableLoading = false
      }).catch(()=>{
        this.tableLoading = false
      })
    },
  },

}
</script>